<template>
  <a-drawer
      :title="title"
      placement="right"
      :visible="visible"
      @close="closeModal"
      :width="800"
      :bodyStyle="{ height: 'calc(100% - 110px)' }"
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane v-for="tab of TABLIST" :key="tab.key" :tab="tab.title"/>
    </a-tabs>
    <section
        class="content mt-10"
        v-show="activeKey == 'copyText'"
    >
      <card-item :content="copyContent" @changeTableField="changeTableField"
                 :tableFields="tableFields" :key="tableKeys"/>

    </section>
    <a-form
        ref="formRef"
        layout="vertical"
        :model="formState"
        @finish="onSubmit"
        :rules="rules"
        class="mt-10"
    >
      <section
          class="content"
          v-show="activeKey == 'upLoad'"
      >
        <a-row :gutter="[16, 8]">
          <a-col :span="24">
            <a-form-item label="收款模板名称" name="name">
              <a-input
                  placeholder="请输入收款模板名称"
                  v-model:value="formState.name"
              />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="上传模板" name="template_path">
              <a-row
                  justify="space-between"
                  class="file-list"
                  v-if="fileName && id"
                  @click="previewClick"
              >
                <a-col>
                  <a-space>
                    <LinkOutlined/>
                    <a>{{ fileName }}</a>
                  </a-space>
                </a-col>
              </a-row>
              <a-upload-dragger
                  v-model:fileList="fileList"
                  name="file"
                  :multiple="false"
                  :action="$utils.fileAction"
                  :headers="{ 'org-token': $store.getters.token }"
                  :showUploadList="false"
                  @change="handleUploadChange"
                  accept=".docx"
                  :data="{
                  dir: 'org_contract_leases',
                  scene: 'contractTemplate',
                }"
              >
                <template v-if="fileList.length">
                  <p class="ant-upload-drag-icon">
                    <FileTextOutlined/>
                  </p>
                  <p class="ant-upload-text">
                    {{ fileList[0].name }}
                  </p>
                </template>
                <template v-else>
                  <p class="ant-upload-drag-icon">
                    <InboxOutlined/>
                  </p>
                  <p class="ant-upload-text">
                    拖拽文件至虚线款内或点击此区域上传文件
                  </p>
                  <p class="ant-upload-hint">文档只支持docx格式</p>
                </template>
              </a-upload-dragger>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="应用楼宇" name="build_bind">
              <a-alert
                  v-if="disabledTree"
                  show-icon
                  type="warning"
                  message="该审批流程原来绑定的项目/楼宇，您未全部选中，无法修改。"
                  class="mb-10"
              />
              <ChooseHousingResources
                  v-if="visible"
                  checkType="build"
                  :allDisabled="disabledTree"
                  :defaultChecked="{ buildList: checkedBuildList }"
                  @request="$utils.commonRequest"
                  @getResult="getResult"
                  @error="setCheckedError"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </section>
      <div class="drawer-footer">
        <a-button class="mr-10" @click="closeModal">取消</a-button>
        <a-button type="primary" html-type="submit">保存</a-button>
      </div>
    </a-form>

    <!-- 预览 -->
    <ElectronContractModal
        :visible="electronContractVisible"
        :urlData="previewUrlData"
        :esignDetail="{
        esignCheck: true,
      }"
        title="在线预览"
        @close="electronContractVisible = false"
    />
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import {
  InboxOutlined,
  FileTextOutlined,
  LinkOutlined,
} from "@ant-design/icons-vue";
import store from "../../../../store";
import {ChooseHousingResources} from "bl-common-vue3";
import ElectronContractModal from "../../../../components/ElectronContractModal/index.vue";
import CardItem from '@/views/contract/RetreatAgreement/modules/CardItem.vue'

export default defineComponent({
  name: "addTemplate",
  components: {
    CardItem,
    ChooseHousingResources,
    defineComponent,
    InboxOutlined,
    FileTextOutlined,
    ElectronContractModal,
    LinkOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const closeModal = () => {
      formRef.value.resetFields();
      context.emit("onCancel");
    };

    const formState = reactive({
      name: "",
      build_bind: null,
      template_path: "",
      table_fields: {},
    });
    const formRef = ref();

    const rules = {
      name: [
        {
          required: true,
          message: "请输入便于辨别的收据模板名称",
        },
      ],
      template_path: [
        {
          required: true,
          message: "请上传模板",
        },
      ],
      build_bind: [
        {
          required: true,
          message: "请选择应用楼宇",
        },
      ],
    };

    const state = reactive({
      billInfo: [],
      houseInfo: [],
      receiptInfo: [],
      tradeParty: [],
      villiageData: [],
      TABLIST: [
        {title: "复制关键字", key: "copyText"},
        {title: "上传收据打印模板", key: "upLoad"},
      ],
      checkedBuildList: [],
      disabledTree: false,
      tableFields: {},
    });
    const activeKey = ref(state.TABLIST[0].key);

    /** 选择房源 */
    const setCheckedError = (e) => {
      state.disabledTree = true;
    };
    const getResult = (info) => {
      if (state.disabledTree) {
        return;
      }
      const {villageList, buildList} = info;
      let list = [];
      if (villageList.length) {
        for (let village of villageList) {
          list = [...list, ...village.children];
        }
      }
      if (buildList.length) {
        list = [...list, ...buildList];
      }
      state.checkedBuildList = list;
      const buildData = utils.getProjectBuildByBuildList(
          state.checkedBuildList
      );
      formState.build_bind = {
        villageIds: buildData.villageId,
        buildIds: buildData.buildId,
        room: [],
      };
    };


    const copyContent = ref([]);
    const tableKeys = ref(0);
    const templateInit = () => {
      request.get("/org", "/receipt/templateInit").then((res) => {
        state.billInfo = res.initData.billInfo;
        state.houseInfo = res.initData.houseInfo;
        state.receiptInfo = res.initData.receiptInfo;
        state.tradeParty = res.initData.tradeParty;
        copyContent.value = []

        copyContent.value.push(
            {
              key: "receiptInfo",
              list: state.receiptInfo,
              title: "收据信息"
            }
        )
        copyContent.value.push(
            {
              key: "tradeParty",
              list: state.tradeParty,
              title: "交收款方"
            }
        )
        copyContent.value.push(
            {
              key: "houseInfo",
              list: state.houseInfo,
              title: "房源信息"
            }
        )
        copyContent.value.push(
            {
              key: "billInfo",
              list: state.billInfo,
              title: "账单信息"
            }
        )
      });
    };

    // 文件上传
    const fileList = ref([]);
    const fileName = ref("");
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              file.previewUrl = file.response.data.previewUrl;
              formState.template_path = file.url;
              fileName.value = file.name;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        formState.template_path = "";
        fileName.value = "";
      }
      fileList.value = resFileList;
    };

    // 预览
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});
    const previewClick = () => {
      if (props.id) {
        previewUrlData.value = {
          previewUrl: fileList.value[0].previewUrl,
          url: fileList.value[0].url,
        };
        electronContractVisible.value = true;
        return;
      }
      previewUrlData.value = {
        previewUrl: fileList.value[0].previewUrl,
        url: fileList.value[0].url,
      };
      electronContractVisible.value = true;
    };

    // 提交
    const onSubmit = () => {
      formState.table_fields = state.tableFields;
      console.log(formState, "formState");
      if (props.id) {
        formState.id = props.id;
        request.put("/org", "/receipt/templateEdit", formState).then((res) => {
          message.success("修改成功");
          context.emit("success");
        });
        return;
      }
      request.post("/org", "/receipt/templateAdd", formState).then((res) => {
        message.success("保存成功");
        context.emit("success");
      });
    };

    const handleTextCopy = (item) => {
      utils.copyText(item);
    };

    const template = () => {
      request
          .get("/org", "/receipt/templateDetail", {id: props.id})
          .then((res) => {
            const {detail} = res;
            setModelRef({
              name: detail.name,
            });
            formState.build_bind = detail.build_bind;
            if (detail?.build_bind?.buildIds) {
              state.checkedBuildList = detail.build_bind.buildIds.map((id) => ({
                id,
              }));
            }
            let file = {};
            file.url = detail.template_path;
            file.name = detail.name;
            formState.template_path = detail.template_path;

            fileList.value = fileList.value.concat(file);
            if (detail.online_preview) {
              fileList.value[0].previewUrl = detail.online_preview.previewUrl;
            }
            fileName.value = detail.name;

            if (detail?.table_fields) {
              let tableFields = {};
              Object.keys(detail.table_fields).forEach((key) => {
                tableFields[key] = detail.table_fields[key].map((v) => {
                  v.isDetail = true;
                  return v;
                });
              });
              formState.table_fields = _.cloneDeep(tableFields);
              state.tableFields = _.cloneDeep(tableFields);
              tableKeys.value++;
            }
          });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        formState[key] = state[key];
      }
    };

    const uploadShow = computed(() => {
      return props.id ? false : true;
    });

    const title = computed(() => {
      return props.id ? "编辑收据模板" : "新增收据模板";
    });
    const init = () => {
      templateInit();
      if (props.id) {
        template();
      }
    };

    const visibleChange = (visible, item) => {
      if (item?.table?.list?.length) {
        item.visible = visible;
      } else {
        item.visible = false;
      }
    };

    const changeCheck = (e, listItem, tabItem) => {
      tabItem.checked = e.target.checked || false;
      state.tableFields[listItem.table.name] = listItem.table.list;
    };

    const filterList = (list, name) => {
      let haveCheck = false;
      Object.keys(state.tableFields).forEach((keys) => {
        if (keys === name) {
          haveCheck = true;
          list = list.map((v) => {
            let result = state.tableFields[keys].filter(
                (item) => item.name == v.name
            )[0];
            if (result) {
              v.checked = Object.hasOwn(result, "checked")
                  ? result.checked
                  : true;
            } else {
              v.checked = false;
            }
            return v;
          });
        }
      });
      if (!haveCheck) {
        list = list.map((v) => {
          v.checked = true;
          return v;
        });
      }
      return list;
    };


    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            fileList.value = [];
            state.checkedBuildList = [];
            state.disabledTree = false;
            fileName.value = "";
            formState.table_fields = {};
            state.tableFields = {};
            tableKeys.value = 0;
            copyContent.value = []
          }
        }
    );

    const changeTableField = (name, list) => {
      state.tableFields[name] = list;
    };

    return {
      title,
      activeKey,
      formState,
      rules,
      formRef,
      uploadShow,
      fileList,
      closeModal,
      onSubmit,
      ...toRefs(state),
      handleTextCopy,
      handleUploadChange,
      setCheckedError,
      getResult,
      previewClick,
      previewUrlData,
      electronContractVisible,
      fileName,
      filterList,
      changeCheck,
      visibleChange,
      copyContent,
      changeTableField,
      tableKeys,

    };
  },
});
</script>

<style lang="less" scoped>
.descriptions {
  margin-bottom: 10px;

  .tag-list {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.file-list {
  cursor: pointer;
  padding: 1px 5px;
  margin-bottom: 10px;
}

.file-list:hover {
  background: #f5f5f5;
  transition: 0.5s ease;
}
</style>
